/*
 * Copyright 2020-2025 the original author or authors.
 * You cannot use this file unless authorized by the author.
 */

package org.ipig.commons.helper;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * gson 助手
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id: GsonHelper.java 3 2020-01-21 09:36:33Z ts <comchnts@163.com> $$
 * @since 1.0
 */
public final class GsonHelper {
    /**
     * Gson对象
     **/
    private volatile static Gson gson;

    /***
     * 构造函数
     */
    private GsonHelper() {
    }

    /**
     * 获得Gson实例
     * 懒加载进行双重check
     *
     * @return Gson
     */
    public static Gson getInstance() {
        if (gson == null) {
            synchronized (GsonHelper.class) {
                if (gson == null) {
                    gson = new Gson();
                }
            }
        }
        return gson;
    }


    /**
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        return getInstance().toJson(object);
    }

    public static <T> T fromJson(String json, Type typeOfT) {
        T target = (T) getInstance().fromJson(json, typeOfT);
        return target;
    }

    public static String toJson(Object object, Class pojoClass) {
        return getInstance().toJson(object, pojoClass);
    }

    /**
     * Parse json to map
     *
     * @param json
     * @return
     */
    public static Map<String, String> parse2Map(String json) {
        Type stringStringMap = new TypeToken<Map<String, String>>() {
        }.getType();
        Map<String, String> map = getInstance().fromJson(json, stringStringMap);
        return map;
    }
}
